package com.zhumo.sz.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.base.Strings;
import com.zhumo.sz.common.CommonInsert;
import com.zhumo.sz.common.CustomLogServerConfig;
import com.zhumo.sz.common.easyexcel.EasyExcelReader;
import com.zhumo.sz.common.utils.DateFormatUtil;
import com.zhumo.sz.entity.bus.*;
import com.zhumo.sz.entity.user.UserInfo;
import com.zhumo.sz.gaode.*;
import com.zhumo.sz.mapper.TransitMapper;
import com.zhumo.sz.mapper.UserMapper;
import com.zhumo.sz.mock.RandomGenerator;
import com.zhumo.sz.mock.TrafficMocker;
import com.zhumo.sz.service.TransitService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.protocol.types.Field;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.util.StringUtil;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TransitServiceImpl implements TransitService {


    @Autowired
    private TransitMapper transitMapper;

    @Autowired
    private UserMapper userMapper;

    private static GaoDeAddressProcessor gaoDeAddressProcessor;

    public static void InitProcessor() {
        if (gaoDeAddressProcessor != null) {
            if (gaoDeAddressProcessor.getApplicationKey().length() != 32) {
                throw new IllegalArgumentException("高德应用key传递有误");
            }
        } else {
            //默认使用注册的应用key
            gaoDeAddressProcessor = new GaoDeAddressProcessor(CustomLogServerConfig.GaoDE_APPLICATION_KEY);
        }
    }

    /**
     * EXCEL 导入 公交站信息
     *
     * @param version
     * @return
     */
    @Override
    public CommonInsert<BusLineInfo> addBusLine(String version) {
        String filePath = "E:\\毕业\\code\\sz-bigdata\\data\\深圳公交数据.xlsx";
        List<BusLineExcel> busLineExcelList = EasyExcelReader.readAsList(BusLineExcel.class, filePath);
        ArrayList<BusLineInfo> busLineInfoList = new ArrayList<>();
        HashSet<String> codeTample = new HashSet<>();
        //所有营运公司 执行查询
        List<BusOperatorCompany> operatorComList = transitMapper.getAllBusOperatorCom();
        for (BusLineExcel busLineExcel : busLineExcelList) {
//            System.out.println(busLineExcel);
            int tample = codeTample.size();
            BusLineInfo busLineInfo = new BusLineInfo();
            String lineCode = busLineExcel.getLineCode();
            codeTample.add(lineCode);
            if (codeTample.size() != tample) {
                busLineInfo.setLineCode(lineCode);
                busLineInfo.setLineName(lineCode + "路");
                busLineInfo.setStartSiteName(busLineExcel.getStartStation());
                busLineInfo.setTerminalSiteName(busLineExcel.getEndStation());
                //上下行站点 有顺序性
                busLineInfo.setUpstreamRouteStation(
                        busLineExcel.getHighThroughStations().replaceAll("\\s", "")
                                .replaceAll("、", ",")
                );
                busLineInfo.setDownwardRouteStation(
                        busLineExcel.getLowThroughStations().replaceAll("\\s", "")
                                .replaceAll("、", ",")
                );
                for (BusOperatorCompany busOperatorCompany : operatorComList) { // num < 10
                    if (busOperatorCompany.getName().equals(busLineExcel.getYhName())) {
                        busLineInfo.setOperatorComId(busOperatorCompany.getComId());
                        break;
                    }
                }
                //班次时间
                busLineInfo.setClasses("6min");
                busLineInfo.setEarliestDepartureTime("6:00");
                busLineInfo.setLastDepartureTime("22:00");
                busLineInfo.setUnitPrice(new BigDecimal("2.00"));
                busLineInfo.setLinePrice(new BigDecimal("7.00")); //深圳市标准
                busLineInfo.setEnabled(true);
                busLineInfo.setOpenTime("2018-01-01"); //政府数据为空 暂时统一赋值
                busLineInfo.setVersion(version);
                busLineInfoList.add(busLineInfo);
            }
        }
//        busLineInfoList.forEach(System.out::println);
//        return null;
        int result = transitMapper.addBusLine(busLineInfoList);
        return new CommonInsert<>(busLineInfoList.size(), result);
    }

    /**
     * 插入地铁站站点信息 从Excel中解析
     *
     * @param version
     * @return
     */
    @Override
    public CommonInsert<BusSiteInfo> addBusStation(String version) {
        String filePath = "E:\\毕业\\code\\sz-bigdata\\data\\深圳公交数据.xlsx";
        ArrayList<BusSiteInfo> collect = new ArrayList<>();
        List<BusLineExcel> lineExcelList = EasyExcelReader.readAsList(BusLineExcel.class, filePath);
        HashSet<String> siteNameSet = new HashSet<>(); //线路站点可能重合
        for (BusLineExcel busLineExcel : lineExcelList) {
            if (Objects.nonNull(busLineExcel.getHighThroughStations()) && !busLineExcel.getHighThroughStations().equals(" ") &&
            !busLineExcel.getHighThroughStations().equals("/")) {
                siteNameSet.addAll(Arrays.asList(busLineExcel.getHighThroughStations()
                        .replaceAll("\\s", "").split("、")));
            }
            if (Objects.nonNull(busLineExcel.getLowThroughStations()) && !busLineExcel.getLowThroughStations().equals(" ") &&
                    !busLineExcel.getHighThroughStations().equals("/")) {
                siteNameSet.addAll(Arrays.asList(busLineExcel.getLowThroughStations()
                        .replaceAll("\\s", "").split("、")));
            }
        }
        HashSet<Long> codeSet = new HashSet<>();
        int count = 0;
        for (String siteName : siteNameSet) {
            BusSiteInfo busSiteInfo = new BusSiteInfo();
            busSiteInfo.setSiteName(siteName);
            while (true){
                long rode = Long.parseLong(RandomGenerator.generateRandomNumber(8));
                if (!codeSet.contains(rode)){
                    busSiteInfo.setSiteCode(rode);
                    codeSet.add(rode);
                    break;
                }
            }
            //请求高德poi 根据地点获取经纬度 然后反编码获取poi
            InitProcessor();
            String name = "广东省深圳市" + siteName + "公交车站";
            GaoDeGeoArea gaoDeGeoArea = gaoDeAddressProcessor.processGeocoAddress(name, "JSON");
            String lat = gaoDeGeoArea.getLat();
            String lng = gaoDeGeoArea.getLng();
            busSiteInfo.setDistrict(gaoDeGeoArea.getDistrict());
            GaoDeResGeoArea gaoDeResGeoArea = gaoDeAddressProcessor.processReverseCode(
                    lng + "," + lat,
                    "all", "200",
                    "公园|旅游景点|商场|购物中心|商务写字楼|政府及社会团体相关|政府机关相关|国家级机关及事业单位|住宅区|别墅|住宅小区|综合医院",
                    "1", "JSON");
            if (Objects.nonNull(gaoDeResGeoArea)) {
                JSONArray jsonArray = JSONArray.parseArray(gaoDeResGeoArea.getPois());
                HashMap<String, ArrayList<Poi>> map = PoiParser.parseGaodeResponse(jsonArray);
                FirstPoi<String> poi = PoiParser.filePoi(map, FirstPoi.class);
                busSiteInfo.setPoi(poi);
                busSiteInfo.setTown(gaoDeResGeoArea.getTown());
                busSiteInfo.setTownCode(gaoDeResGeoArea.getTownCode());
                //解析道路
                busSiteInfo.setRoad(JSON.toJSONString(Road.parseRoadForMysql(gaoDeResGeoArea.getRoads())));
                //解析商圈
                busSiteInfo.setBusiness(JSON.toJSONString(Business.parseBusForMysql(gaoDeResGeoArea.getBusinessAreas())));
            }
            //版本时间
            busSiteInfo.setOpeningTime("2018-01-01");
            busSiteInfo.setVersion(version);
            collect.add(busSiteInfo);
            log.info("插入公交站点: " + busSiteInfo.getSiteName() );
            count ++;
            System.out.println(count);
            if (count > 1000){
                break;
            }
        }
        int result = transitMapper.addBusStation(collect);
        return new CommonInsert<BusSiteInfo>(collect.size(),result);
    }

    /**
     * 导入长途客运站信息 Excel 处理
     * @param version
     * @return
     */
    @Override
    public CommonInsert<LengthBusStationInfo> addLengthBusStation(String version) {
        String filePath = "E:\\毕业\\code\\sz-bigdata\\data\\深圳长途客运站数据.xlsx";
        ArrayList<LengthBusStationInfo> collect = new ArrayList<>();
        List<LengthBusStationInfo> lengthBusStationInfoList = EasyExcelReader.readAsList(LengthBusStationInfo.class, filePath);
        System.out.println(lengthBusStationInfoList);
        for (LengthBusStationInfo lengthBusStationInfo : lengthBusStationInfoList) {
            //todo 市辖区编码无法直接获取 需要查公共地区表 后期优化 目前置空
            if (lengthBusStationInfo.getStationName().contains("深圳")) {
                lengthBusStationInfo.setLevel("2");
            } else {
                lengthBusStationInfo.setLevel("1");
            }
            lengthBusStationInfo.setVersion(version);
            lengthBusStationInfo.setOpenYear("2018");
            lengthBusStationInfo.setIsEnabled(true);
            lengthBusStationInfo.setCreateTime(Timestamp.valueOf(DateFormatUtil.toYmdHms(System.currentTimeMillis())));
            collect.add(lengthBusStationInfo);
        }
        int result = transitMapper.addLengthBusStation(collect);
        return new CommonInsert<>(collect.size(),result);
    }

    /**
     * 增加长途客运站班次信息 每个客车最多有五个班次
     */
    @Override
    public CommonInsert<LengthBusDepartureScheduleInfo> addLengthBusSchedule(String stations,int depNum) {
        if (Objects.isNull(stations)){
            throw new RuntimeException("参数不合法");
        }
        //todo 目前代码只支持全量刷新  后期维护
        HashSet<String> stationCodeSet = new HashSet<>(transitMapper.getAllLengthStationCode());
        ArrayList<LengthBusDepartureScheduleInfo> scheduleCollect = new ArrayList<>();
        if (stations.equals("all")){ //所有站点增加 需要清表
            int code = transitMapper.clearAllLengthBusScheduler();
            if (code != 0){
                return new CommonInsert<LengthBusDepartureScheduleInfo>(-1,0);
            }
            List<LengthBus> lengthBusList = transitMapper.getAllLengthBusInfo(); //为每辆汽车增加班次 默认五个班次
            for (LengthBus lengthBus : lengthBusList) {
//                HashSet<String> batchSet = new HashSet<>(); //维护班次号码 弃用
                for (int i = 0; i < depNum; i++) {
                    LengthBusDepartureScheduleInfo scheduleInfo = new LengthBusDepartureScheduleInfo();
                    scheduleInfo.setBusId(lengthBus.getBusId());
                    scheduleInfo.setDriverId(lengthBus.getDriverId());
                    scheduleInfo.setOnBoardTicketSellerId(lengthBus.getOnBoardTicketSellerId()); //司机与检票员
                    scheduleInfo.setSchId(scheduleInfo.getBusId() + "-" + "2024" + "-" + "00" + i);
                    scheduleInfo.setStationCode(lengthBus.getStationCode());
                    //查询汽车所在的公交站信息
                    scheduleInfo.setIsCity(false);
                    LengthBusStationInfo stationInfo = transitMapper.getStationByCode(scheduleInfo.getStationCode());
                    scheduleInfo.setStartPoint("深圳市" + stationInfo.getDistrict());
                    scheduleInfo.setEndPoint("广东省" + CustomLogServerConfig.PROVINCE_CITY_GD[new Random().nextInt(CustomLogServerConfig.PROVINCE_CITY_GD.length)]);
                    if (scheduleInfo.getEndPoint().contains("深圳")){
                        scheduleInfo.setAmount(BigDecimal.valueOf(15));
                        scheduleInfo.setIsCity(true);
                    }
                    scheduleInfo.setAmount(BigDecimal.valueOf(CustomLogServerConfig.TICKER_AMOUNT[new Random().nextInt(CustomLogServerConfig.TICKER_AMOUNT.length)]));
                    scheduleInfo.setIsEnabled(true);
                    scheduleInfo.setIsDeleted(false);
                    //判断时间 早上起点推算 理论到达时间暂时不可用
                    scheduleInfo.setDepartureTime( 7 + i * 2);
                    scheduleCollect.add(scheduleInfo);
                }
            }
        }else {
            return new CommonInsert<LengthBusDepartureScheduleInfo>(0,-1);
        }
        //执行写入
        int result = transitMapper.addLengthBusScheduler(scheduleCollect);
        return new CommonInsert<LengthBusDepartureScheduleInfo>(scheduleCollect.size(),result);
    }

    /**
     * 增加市内公交乘坐订单 v2024-03-24
     * 公交车 线路 定义即路次 如M182 M197
     * @param num 订单数量
     * @param date 订单日期
     * @param type 生成场景 离线/实时
     */
    @Override
    public CommonInsert<BusOrderDetail> addBusOrder(int num, String date, String type) {
        if (Objects.isNull(type) || (! type.equals("batch") && ! type.equals("realtime"))){
            throw new RuntimeException("参数不合法");
        }
        //根据线路查询站点
        List<BusLineInfo> busLineList = transitMapper.getAllBusLine();
        ArrayList<BusOrderDetail> busOrderCollect = new ArrayList<>();
        //获取历史订单
        HashSet<String> historyOrderSet = new HashSet<>(transitMapper.getAllHistoryBusOrder());
        //获取全量用户
        List<UserInfo> userList = userMapper.selectAllUser();
        HashSet<String> exitedUserSet = new HashSet<>();

        HashSet<String> orderSet = new HashSet<>();
        for (int i = 0; i < num; i++) {
            BusOrderDetail busOrderDetail = new BusOrderDetail();
            while (true) {
                String orderId = "2024" + RandomGenerator.generateRandomNumber(12);
                if (!historyOrderSet.contains(orderId) && !orderSet.contains(orderId)) {
                    busOrderDetail.setBusOrderId(orderId);
                    orderSet.add(orderId);
                    break;
                }
            }
            busOrderDetail.setOld(false);
            busOrderDetail.setStu(false);
            while (true){
                UserInfo userInfo = userList.get(new Random().nextInt(userList.size()));
                if (! exitedUserSet.contains(userInfo.getUserId())){
                    exitedUserSet.add(userInfo.getUserId());
                    busOrderDetail.setUserId(userInfo.getUserId());
                    if ( 2024 - Long.parseLong(userInfo.getBirthday().substring(0,4)) > 60){
                        busOrderDetail.setOld(true);
                    }if ( 2024 - Long.parseLong(userInfo.getBirthday().substring(0,4)) < 18){
                        busOrderDetail.setStu(true);
                    }
                    break;
                }
            }
            busOrderDetail.setDeformed(TrafficMocker.isDeformed(busOrderDetail.isOld())); //判断残疾人
            BusLineInfo lineInfo = busLineList.get(new Random().nextInt(busLineList.size()));
            String lineCode = lineInfo.getLineCode(); //路次编码
            busOrderDetail.setLineCode(lineCode);
            // 执行查询 站点信息 优先判断上下行 并记录上下车站点的索引 下车索引必须大于上车索引
            String[] sites = null;
            if (TrafficMocker.isBusCityUpper()){
                busOrderDetail.setUpper(true);
                sites = lineInfo.getUpstreamRouteStation().split(",");
            }else {
                busOrderDetail.setUpper(false);
                sites = lineInfo.getDownwardRouteStation().split(",");
            }
            //todo 记录上下车索引
            int startTag = 0;
            while (true){
                startTag = new Random().nextInt(sites.length);
                if (startTag != sites.length -1){
                    String startSiteName = sites[startTag];
                    busOrderDetail.setStartSiteName(startSiteName);
                    BusSiteInfo startSite = transitMapper.getBusSiteByName(startSiteName);
                    busOrderDetail.setStartSiteCode(startSite.getSiteCode());
                    break;
                }
            }
//            String startSiteName = sites[new Random().nextInt(sites.length)];
//            busOrderDetail.setStartSiteName(startSiteName);
//            BusSiteInfo startSite = transitMapper.getBusSiteByName(startSiteName);
//            busOrderDetail.setStartSiteCode(startSite.getSiteCode());
            // 下车点
            int endTag = 0;
            while (true){
                endTag = new Random().nextInt(sites.length);
                if ( endTag > startTag ){
                    String endSiteName = sites[endTag];
                    busOrderDetail.setEndSiteName(endSiteName);
                    BusSiteInfo endSite = transitMapper.getBusSiteByName(endSiteName);
                    busOrderDetail.setEndSiteCode(endSite.getSiteCode());
                    break;
                }
            }
            //上下车时间
            if (type.equals("realtime")){
                busOrderDetail.setEndTime(Timestamp.valueOf(DateFormatUtil.toYmdHms(System.currentTimeMillis())));
            }else {
                busOrderDetail.setEndTime(Timestamp.valueOf(RandomGenerator.generateRandomTimeStamp(date)));
            }
            int throughSiteNum = endTag - startTag;
            busOrderDetail.setStartTime(Timestamp.valueOf(RandomGenerator.generateStartTime(String.valueOf(busOrderDetail.getEndTime()), 2L * 60 * throughSiteNum )));
            busOrderDetail.setOrderTime(Timestamp.valueOf(RandomGenerator.generateStartTime(String.valueOf(busOrderDetail.getEndTime()), (long) 1000)));
            //订单金额
            BigDecimal orderAmount = throughSiteNum > 12 ? BigDecimal.valueOf(7.00) : BigDecimal.valueOf(0.5 * throughSiteNum);
            busOrderDetail.setOrderAmount(orderAmount);
            BigDecimal paymentAmount = orderAmount;
            if (busOrderDetail.isOld() || busOrderDetail.isDeformed()) { //残疾人 老年人免费 深圳关爱通减免 因此没有支付时间
                busOrderDetail.setPaymentAmount(BigDecimal.ZERO);
                busOrderDetail.setTicketType("老年卡");
                busOrderDetail.setCarePassReductionAmount(paymentAmount);
            }else {
                if (busOrderDetail.isStu()){
                    paymentAmount = orderAmount.divide(BigDecimal.valueOf(2),3, RoundingMode.HALF_UP);
                    busOrderDetail.setCarePassReductionAmount(orderAmount.divide(BigDecimal.valueOf(2),3, RoundingMode.HALF_UP));
                }
                // 支付方式 门票类型 扫码方式
                busOrderDetail.setTicketType("线下投币");
                busOrderDetail.setPaymentMethod("现金");
                if (TrafficMocker.isTicketOnline()){
                    busOrderDetail.setTicketType("电子票");
                    if (TrafficMocker.isSZTUser()){
                        busOrderDetail.setApp("深圳通");
                        busOrderDetail.setPaymentMethod(TrafficMocker.getOnlinePaymentType());
                    }else {
                        busOrderDetail.setApp("支付宝");
                        busOrderDetail.setPaymentMethod("支付宝");
                        if (TrafficMocker.isAppActActive()){
                            paymentAmount = paymentAmount.subtract(BigDecimal.ONE);
                            busOrderDetail.setAliPlayReductionAmount(BigDecimal.ONE);
                        }
                    }
                }
                busOrderDetail.setPaymentAmount(paymentAmount.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : paymentAmount);
                busOrderDetail.setPaymentTime(Timestamp.valueOf(RandomGenerator.generateStartTime(String.valueOf(busOrderDetail.getEndTime()),2 * 1000)));
            }
            busOrderCollect.add(busOrderDetail);
        }
        int result = transitMapper.addBusOrder(busOrderCollect);
        return new CommonInsert<BusOrderDetail>(busOrderCollect.size(),result);
    }

    /**
     * 增加长途客运订单 v2024-03-24 每次生成当天的数据
     * @param num
     * @param date
     * @param type
     * @return
     */
    @Override
    public CommonInsert<LengthBusTickingDetail> addLengthBusOrder(int num, String date, String type) {
        if (Objects.isNull(type) || (! type.equals("batch") &&  !type.equals("realtime"))){
            throw new RuntimeException("参数传递异常");
        }
        ArrayList<LengthBusTickingDetail> lengthBusTicketCollect = new ArrayList<>();
        HashSet<String> orderSet = new HashSet<>(); //用户量较大 不用查全量
        HashSet<String> userSet = new HashSet<>();
        List<UserInfo> userList = userMapper.sampleUser(num);
        //获取所有长途站点
        List<LengthBusStationInfo> stationList = userMapper.getAllLengthBusStation();
        for (int i = 0; i < num; i++) {
            LengthBusTickingDetail lengthBusTickingDetail = new LengthBusTickingDetail();
            while (true){
                String orderId = RandomGenerator.generateRandomNumber(20);
                if (! orderSet.contains(orderId)){
                    lengthBusTickingDetail.setOrderId(Long.valueOf(orderId));
                    orderSet.add(orderId);
                    break;
                }
            }
            while (true){
                UserInfo user = userList.get(new Random().nextInt(userList.size()));
                String userId = user.getUserId();
                if (! userSet.contains(userId)){
                    userSet.add(userId);
                    lengthBusTickingDetail.setCardId(user.getOneCard());
                    //确认年龄sex
                    lengthBusTickingDetail.setOrderedName(user.getUserName());
                    int age = Integer.parseInt(lengthBusTickingDetail.getCardId().substring(7,11));
                    lengthBusTickingDetail.setIsStu(age < 18);
                    lengthBusTickingDetail.setIsOld(age > 60);
                    break;
                }
            }
            lengthBusTickingDetail.setStationCode(stationList.get(new Random().nextInt(stationList.size())).getStationCode());
            String siteCode = lengthBusTickingDetail.getStationCode();
            //查询班次
            List<LengthBusDepartureScheduleInfo> scheduleInfoList = transitMapper.getSchByStation(siteCode);
            LengthBusDepartureScheduleInfo scheduleInfo = scheduleInfoList.get(new Random().nextInt(scheduleInfoList.size()));
            lengthBusTickingDetail.setSchId(scheduleInfo.getSchId());
            lengthBusTickingDetail.setWindow(scheduleInfo.getStationCode() + "-" + new Random().nextInt(15)); //服务窗口
            lengthBusTickingDetail.setDepartureTime(scheduleInfo.getDepartureTime());
            lengthBusTickingDetail.setDate(
                    date.substring(0,date.length()-1) +
                            (date.substring(date.length()-1)) + String.valueOf(new Random().nextInt(14))
            ); //当前日期  +  15天以内
            if (type.equals("batch")) {
                lengthBusTickingDetail.setOrderPutTime(Timestamp.valueOf(RandomGenerator.generateRandomTimeStamp(date)));
                lengthBusTickingDetail.setPaymentTime(Timestamp.valueOf(RandomGenerator.generateStartTime(
                        lengthBusTickingDetail.getOrderPutTime().toString(), new Random().nextInt(60 * 5) * -1
                )));
                lengthBusTickingDetail.setTicketTime(Timestamp.valueOf(RandomGenerator.generateStartTime(
                        lengthBusTickingDetail.getPaymentTime().toString(), -1))
                );
            }else {
                lengthBusTickingDetail.setTicketTime(Timestamp.valueOf(RandomGenerator.generateRandomTimeStamp(date)));
                lengthBusTickingDetail.setPaymentTime(Timestamp.valueOf(RandomGenerator.generateStartTime(
                        String.valueOf(lengthBusTickingDetail.getTicketTime()),1)));
                lengthBusTickingDetail.setOrderPutTime(Timestamp.valueOf(RandomGenerator.generateStartTime(
                        String.valueOf(lengthBusTickingDetail.getPaymentTime()), -1 * 300
                )));
            }
            BigDecimal orderAmount = scheduleInfo.getAmount();
            lengthBusTickingDetail.setOrderAmount(orderAmount);
            if (lengthBusTickingDetail.getIsOld() || lengthBusTickingDetail.getIsStu()){
                lengthBusTickingDetail.setPaymentAmount(orderAmount.divide(BigDecimal.valueOf(2)));
            }
            lengthBusTickingDetail.setCreateTime(lengthBusTickingDetail.getTicketTime());
            lengthBusTicketCollect.add(lengthBusTickingDetail);
        }
        int result = transitMapper.addLengthBusTickets(lengthBusTicketCollect);
        return new CommonInsert<LengthBusTickingDetail>(lengthBusTicketCollect.size(),result);
    }

    /**
     * 增加长途客运汽车 增量
     * @param num
     * @return
     */
    @Override
    public CommonInsert<LengthBus> addLengthBus(int num) {
        List<LengthBus> existedLengthBusList = transitMapper.getAllLengthBusInfo();
        Set<Long> existedIdSet = existedLengthBusList.stream().map(LengthBus::getBusId).collect(Collectors.toSet());
        HashSet<Long> lengthIDSet = new HashSet<>();
        //执行查询获取所有station
        List<String> stationCodeList = transitMapper.getAllLengthStationCode();
        ArrayList<LengthBus> lengthBusCollect = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            LengthBus lengthBus = new LengthBus();
            while (true){ //设置id
                Long lengthBusId = Long.parseLong(RandomGenerator.generateRandomNumber(8));
                if (! existedIdSet.contains(lengthBusId) && ! lengthIDSet.contains(lengthBusId)){
                    lengthBus.setBusId(lengthBusId);
                    lengthIDSet.add(lengthBusId);
                    break;
                }
            }
            //车牌号与司机标识
            lengthBus.setBusCard("粤B" + RandomGenerator.generateRandomString(5));
            lengthBus.setDriverId(RandomGenerator.generateRandomString(5));
            lengthBus.setOnBoardTicketSellerId(RandomGenerator.generateRandomString(5));
            lengthBus.setIsEnabled(true);
            lengthBus.setRegionYear("2018");
            lengthBus.setOnUseTime(Timestamp.valueOf(RandomGenerator.generateRandomTimeStamp("2021-01-01")));
            lengthBus.setStationCode(stationCodeList.get(new Random().nextInt(stationCodeList.size())));
            lengthBus.setCreateTime(Timestamp.valueOf(DateFormatUtil.toYmdHms(System.currentTimeMillis())));
            lengthBusCollect.add(lengthBus);
            //分配站点
        }
        //执行写入
//        lengthBusCollect.forEach(System.out::println);
        int result = transitMapper.batchAddLengthBus(lengthBusCollect);
        return new CommonInsert<LengthBus>(lengthBusCollect.size(),result);
    }

//    public static void main(String[] args) {
////        String path = "D:\\model\\sz-bigdata\\data\\深圳公交数据.xlsx";
////        TransitServiceImpl transitService = new TransitServiceImpl();
//////        String lengthPath = "D:\\model\\sz-bigdata\\data\\深圳长途客运站数据.xlsx";
//////        CommonInsert<BusLineInfo> addBusLine = transitService.addBusLine("2024.1", path);
////        transitService.addBusStation("2024.1",path);
//////        transitService.addLengthBusStation("2024.1",lengthPath);
//        TransitServiceImpl transitService = new TransitServiceImpl();
//        transitService.addLengthBus(100);
//    }
}
